﻿using System.Collections.Concurrent;
using Base.FileGateway.Interface;
using Base.FileGateway.PdfConvert.Model;
using WeDonekRpc.Helper;

namespace Base.FileGateway.PdfConvert
{
    internal class UserPdfFileService : IUserPdfFileService
    {
        private static readonly ConcurrentDictionary<string, UserPdfTask> _TaskList = new ConcurrentDictionary<string, UserPdfTask>();

        private static readonly Timer _ClearTask = new Timer(new TimerCallback(_Clear), null, 60000, 60000);

        private static void _Clear ( object? state )
        {
            if ( _TaskList.IsEmpty )
            {
                return;
            }
            int time = HeartbeatTimeHelper.HeartbeatTime - 30;
            string[] taskId = _TaskList.Where(a => a.Value.IsComplete && a.Value.EndTime < time).Select(a => a.Key).ToArray();
            if ( !taskId.IsNull() )
            {
                taskId.ForEach(c =>
                {
                    _ = _TaskList.TryRemove(c, out _);
                });
            }
        }

        private static UserPdfTask _GetTask ( PdfArg arg )
        {
            string taskId = string.Join("_", arg.FileId, arg.DirKey, arg.LinkBizPk.GetValueOrDefault(), arg.Tag ?? string.Empty).GetMd5();
            if ( !_TaskList.TryGetValue(taskId, out UserPdfTask task) )
            {
                task = new UserPdfTask(taskId);
                if ( _TaskList.TryAdd(taskId, task) )
                {
                    task.BeginTask(arg);
                    return task;
                }
                return _GetTask(arg);
            }
            return task;
        }
        public PdfCovertRes GetResult ( string taskId )
        {
            if ( _TaskList.TryGetValue(taskId, out UserPdfTask task) )
            {
                return task.GetResult();
            }
            throw new ErrorException("file.pdf.task.not.find");
        }
        public PdfCovertRes Apply ( PdfArg arg )
        {
            UserPdfTask task = _GetTask(arg);
            return task.GetResult();
        }
    }
}
